<template>
 <div style="height: 100%">
   <navbar class="header-title-01 header-title-06 header-margin border-bottom2">
        <template #title>
            <form action="/">
                <van-search
                    v-model="searchValue"
                    :placeholder="scrollingKeyword"
                    input-align="left"
                    @search="onSearch"
                    @focus="stopScrolling"  @blur="startScrolling"
                />
            </form>
        </template>
    </navbar>
    <div class="content-noBottom white-bg">
        <div style="padding:15px 12px 0">
            <div class="scroller-box" ref="scroller">
                <p @click="historyClick(item)" class="hover-click" v-for="(item,index) in searchKeyData.userKeywords" :key="index">{{item}}</p>
            </div>
        </div>
        <div class="remind-container" v-if="reminderSwitch">
            <p class="font-size14 color999">{{ $t('button_search_tips') }}</p>
            <ul class="reminder-title">
                <li>{{ $t('menu_course') }}</li>
                <li>{{ $t('personal_ls_knowledge') }}</li>
                <li>{{$t('cos_type_map')}}</li>
                <li>{{$t('konwledge_special_title')}}</li>
                <li>{{$t('personal_user')}}</li>
            </ul>
        </div>
        <div class="white-bg" style="height: calc(100% - 56px);" v-if="startSearch && allSum >= 1">
            <div class="catalog-container" v-if="searchCatalogSwitch">
                <tabs :activeType="type" style="line-height: 30px" :tabs="searchCatalog" @selectType="changeType"></tabs>
            </div>
            <van-pull-refresh v-model="isRefresh" @refresh="onPulldownTop" loading-text="loading" pulling-text="" loosing-text="" style="height: 100%;">
                <van-list v-if="searchAllList.length > 0"
                    v-model="isLoading"
                    :finished="finished"
                    :finished-text="(finished&&total>0) ? $t('no_more') : ''"
                    loding-text="loading"
                    @load="getList"
                    style="padding-bottom: 56px;background: white;">
                    <searchItem  v-for="(item,i) in searchAllList" :key="i" :item="item" :searchValue="searchValue" @click.native="enterDetail(item)"></searchItem>
                </van-list>
                <div v-else class="white-bg">
                    <div class="box-table" style="width:100%;height:100%;">
                        <div class="box-table-cell" style="text-align: center;">
                            <div class="no-data" style="margin-top: 15px;">
                            <img src="../../../static/images/no-data.png" alt=""/>
                            <p class="color999">{{ $t("no_data") }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </van-pull-refresh>
        </div>
        <div v-if="!isLoading && allSum <= 0" class="white-bg">
            <div class="box-table" style="width:100%;height:100%;">
                <div class="box-table-cell" style="text-align: center;">
                    <div class="no-data" style="margin-top: 15px;">
                    <img src="../../../static/images/no-data.png" alt=""/>
                    <p class="color999">{{ $t("no_data") }}</p>
                    </div>
                </div>
            </div>
        </div>
        <common-loading :isLoading="isLoading"></common-loading>
    </div>
 </div>
</template>

<script>
import tabs from '@/repeatComponents/tab/Tab';
import searchItem from '@/components/search/SearchItem';
import { Search, Toast } from 'vant';
import mixin from '@/components/mixin/Mixin.js';
export default {
    name: 'FreshSearch',
    components: {
        tabs,
        searchItem,
        [Search.name]: Search,
        [Toast.name]: Toast
    },
    computed: {
        // 当前输入框轮播显示
        scrollingKeyword() {
            if (this.searchKeyData.systemKeywords && this.searchKeyData.systemKeywords.length > 0) {
                return this.searchKeyData.systemKeywords[this.currentKeywordIndex];
            }
            return '';
        },
        initHeight() {
            let style = {};
            if (this.searchCatalogSwitch) {
                // style.height = 'calc(100% - 101px)';
            } else {
                style.height = 'calc(100%)';
                style.paddingTop = '56px';
            }
            return style;
        }
    },
    mixins: [mixin],
    data() {
        return {
            searchKeyData: {},
            currentKeywordIndex: 0,
            intervalId: null,
            searchValue: '',
            reminderSwitch: true,
            searchAllList: [], //内容
            countList: {}, //数量集合
            searchCatalogSwitch: false,
            searchCatalog: [],
            total: 0,
            startSearch: false,
            pageNo: 1,
            pageSize: 10,
            isLoading: false,
            type: {},
            finished: false,
            isRefresh: false,
            allSum: 0
        };
    },
    mounted() {
        this.historyKey();
    },
    methods: {
        // 3s轮播一次关键词
        startScrolling() {
            if (this.searchKeyData && this.searchKeyData.systemKeywords && this.searchKeyData.systemKeywords.length > 0) {
                clearInterval(this.intervalId);
                this.intervalId = null;
                this.intervalId = setInterval(() => {
                    if (!this.searchValue) {
                        this.currentKeywordIndex = (this.currentKeywordIndex + 1) % this.searchKeyData.systemKeywords.length;
                    }
                }, 3000);
            }
        },
        // 聚焦停止轮播
        stopScrolling() {
            clearInterval(this.intervalId);
            this.intervalId = null;
        },
        // 获取关键词及历史搜索记录
        historyKey() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/home/search/keywords`
            }).then(res => {
                console.log(res);
                this.searchKeyData = res.data;
                this.startScrolling();
            });
        },
        // 点击历史记录搜索
        historyClick(item) {
            this.searchValue = item;
            this.$refs.scroller.scrollLeft = 0;
            this.onSearch(item);
        },
        async onSearch(val) {
            this.type = 'ALL';
            this.pageNo = 1;
            this.searchText = val;
            this.startSearch = true;
            this.reminderSwitch = false;
            if (!this.searchText && this.searchKeyData && this.searchKeyData.systemKeywords && this.searchKeyData.systemKeywords.length > 0) {
                this.searchText = this.searchKeyData.systemKeywords[this.currentKeywordIndex];
            }
            if (!this.searchText) {
                Toast({message: this.$t('searchNotNull'), forbidClick: true});
                this.reminderSwitch = true;
                return false;
            }
            this.finished = false;
            this.getList('refresh');
            this.getFreshSearchCount();
            // 成功更新历史记录
            this.historyKey();
        },
        /*获取新的搜索接口*/
        async  getFreshSearchDetail(type) {
            this.isLoading = true;
            const res = await this.$axios({
                method: 'GET',
                url: `/app/api/trainee/home/search`,
                params: {
                    keyword: this.searchText,
                    type: type || 'ALL',
                    sort: 'heat-desc',
                    pageNo: this.pageNo,
                    pageSize: this.pageSize,
                    isMobile: true
                }
            });
            this.isLoading = false;
            return res;
        },
        /*获取新的搜索数量*/
        getFreshSearchCount() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/home/search/count`,
                params: {
                    keyword: this.searchText,
                    type: 'ALL',
                    pageNo: 1,
                    pageSize: this.pageSize,
                    isMobile: true
                }
            }).then(res => {
                //封装目录数据
                this.searchCatalogSwitch = true;
                this.allSum = this.countAllSum(res.data);
                this.searchCatalog = this.packageCatalog(res.data);
                this.searchCatalog.sort(this.compare('sum'));
            });
        },
        countAllSum(obj) {
            let sum = 0;
            for (let key in obj) {
                sum = sum + obj[key];
            }
            return sum;
        },
        compare(sum) {
            return function(a, b) {
                let value1 = a[sum];
                let value2 = b[sum];
                return value2 - value1;
            };
        },
        packageCatalog(data) {
            let catalog = [];
            this.searchType.forEach(item => {
                switch (item.type) {
                case 'ALL':
                    item.sum = Number(this.allSum) ? this.allSum : 0;
                    break;
                case 'COURSE': // 课程
                    item.sum = Number(data.courseCount) ? data.courseCount : 0;
                    break;
                case 'KNOWLEDGE': // 知识库
                    item.sum = Number(data.knowledgeCount) ? data.knowledgeCount : 0;
                    break;
                case 'MAP': // 游戏课程
                    item.sum = Number(data.mapCount) ? data.mapCount : 0;
                    break;
                case 'SUBJECT': // 专题培训
                    item.sum = Number(data.subjectCount) ? data.subjectCount : 0;
                    break;
                case 'USER': // 用户
                    item.sum = Number(data.userCount) ? data.userCount : 0;
                    break;
                case 'QUESTION': // 问答
                    item.sum = Number(data.questionCount) ? data.questionCount : 0;
                    break;
                case 'WORK': // 工作圈
                    item.sum = Number(data.workCount) ? data.workCount : 0;
                    break;
                // case 'BULLETIN': // 公告
                //     item.sum = Number(data.bulletinCount) ? data.bulletinCount : 0;
                //     break;
                // case 'ARTICLE': // 资讯
                //     item.sum = Number(data.articleCount) ? data.articleCount : 0;
                //     break;
                }
                catalog.push(item);
            });
            return catalog;
        },
        onPulldownTop() {
            this.isRefresh = true;
            setTimeout(() => {
                this.finished = false;
                this.searchAllList = [];
                this.pageNo = 1;
                this.getList('refresh');
                this.getFreshSearchCount();
                this.isRefresh = false;
            }, 900);
        },
        getList(option) {
            if (this.finished) {
                this.isLoading = false;
                return;
            }
            this.getFreshSearchDetail(this.type).then(res => {
                if (option && option === 'refresh') {
                    this.searchAllList = res.data.results;
                } else {
                    this.searchAllList = [...this.searchAllList, ...res.data.results];
                }
                this.total = res.data.totalRecord;
                if (this.searchAllList.length >= this.total) {
                    this.finished = true;
                }
                this.pageNo++;
            });
        },
        changeType(val) {
            this.pageNo = 1;
            this.type = val;
            this.searchAllList = [];
            this.finished = false;
            this.getList('refresh');
        },
        enterDetail(item) {
            let id = item.id;
            let title = item.title;
            let type = item.type;
            switch (item.mark) {
            case 'COURSE':
                if (type && type === '') { //跳转到公开课

                } else if (type === 'MAP') {

                } else {
                    if (item.itmTrianForm === 3) { // 培训
                        this.$router.push({path: `/certifiedCourse/${id}/0`});
                    } else {
                        this.$router.push({path: `/course/${id}/0`});
                    }
                }
                break;
            case 'KNOWLEDGE':
                if (item.access) {
                    this.$router.push(`/knowledgeDetail/${id}`);
                } else {
                    Toast.fail(this.$t('err_tips_1'));
                }
                break;
            case 'ARTICLE':
                break;
            case 'QUESTION':
                this.$router.push(`/knowDetail/${type}/${id}`);
                break;
            case 'WORK':
                if (item.access) {
                    this.$router.push(`/circle/detail?circleId=${id}`);
                } else {
                    Toast.fail(this.$t('err_tips_1'));
                }
                break;
            case 'MAP':
                this.$router.push({path: '/studyMapDetail', query: {itmId: id, title: title}});
                break;
            case 'SUBJECT':
                this.$router.push({path: '/knowledgeDetail', query: {id, title}});
                break;
            case 'USER':
                this.$router.push(`/personalFile/${id}`);
                break;
            case 'BULLETIN':

                break;
            case 'AUDIOVIDEO':
                this.$router.push({path: `/publicClass/openDetail/${id}`});
                break;
            }
        }
    },
    beforeDestroy() {
        clearInterval(this.intervalId);
        this.intervalId = null; // 销毁时间戳
    }
};
</script>

<style scoped lang="less">
  .remind-container{
    padding: 15px;
    // height: calc(100% - 86px);
    .reminder-title{
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      >li{
        background: #f5f5f5;
        color: #999999;
        border-radius: 2px;
        height: 30px;
        line-height: 30px;
        padding: 0 15px;
        margin: 10px 10px 0 0;
      }
    }
  }
  .content-container{
   background-color: #fff;
  }
  /deep/.van-search{
    background: #fff;
    .van-search__content{
      border-radius: 10px;
      width: 100%;
      height: 30px;
      background: #f5f5f5;
      color: #333;
      margin: 0 auto;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      justify-content: center;
      .van-field__control{
        color: #333;
      }
      input::-webkit-input-placeholder {
        color: #999;
      }
      .van-icon-clear{
        color: #333;
      }
      .van-cell{
        color: #333;
      }
    }
  }
  /deep/.van-nav-bar__content .van-nav-bar__title {
        max-width: 80%;
        width: 80%;
        margin-left: 50px;
    }
 /deep/.van-nav-bar .van-icon-search {
    font-size: 16px;
 }
 .scroller-box{
    display:flex;
    color:#aaa;
    // border: 1px solid;
    width: 100%;
    overflow: hidden;
    overflow-x: scroll;
    white-space: nowrap;
    .hover-click{
        border: 1px solid #cccccc;
        padding: 5px 8px;
        border-radius: 30px;
        margin-right:15px;
        white-space: nowrap;
    }
}
.scroller-box::-webkit-scrollbar {
    display: none; /* 隐藏滚动条 */
}
</style>
